import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_author.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_post_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/post/post_detail_page.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/pd_banner.dart';
import 'package:osc/ui/widgets/post/rich_text_title.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///帖子
class PostList extends StatefulWidget {
  final int catalog;
  final bool showPortrait;
  final bool withBanner;
  final bool richTextTitle;

  /// 1-资讯|4-博客|8-问答
  const PostList({Key key, @required this.catalog, this.showPortrait = false, this.withBanner = false, this.richTextTitle = false}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new PostListState(catalog, showPortrait, withBanner, richTextTitle);
  }
}

class PostListState extends State<PostList> with AutomaticKeepAliveClientMixin<PostList> {
  final int catalog;
  final bool showPortrait;
  final bool withBanner;
  final bool richTextTitle;
  PostListState(this.catalog, this.showPortrait, this.withBanner, this.richTextTitle);

  HttpRepository httpRepository;
  String token;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscPostEntity> list;

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();


  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    switch(catalog){
      case 1:
        token = "e6142fa662bc4bf21083870a957fbd20";
        break;
      case 4:
        token = "df985be3c5d5449f8dfb47e06e098ef9";
        break;
      case 8:
        token = "98d04eb58a1d12b75d254deecbc83790";
        break;

    }
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: withBanner? buildListViewWithBanner() : buildListView(),
    );
  }

  buildListViewWithBanner(){
    return ListView(
      physics: scrollPhysics,
      children: <Widget>[
        PdBanner(catalog: catalog, delay: 5000,),
        buildListView(shrinkWrap: true),
      ],
    );
  }

  buildListView({bool shrinkWrap = false}){
    return ListView.separated(
      shrinkWrap: shrinkWrap,
      physics: scrollPhysics,
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
    );
  }

  buildListItem(int index){
    OscPostEntity item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        jump2PageForResult(PostDetailPage(id: item.id, type: item.type,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
        child: showPortrait? buildPostContentWithPortrait(item) : buildPostContent(item),
      ),
    );
  }

  buildPostContentWithPortrait(OscPostEntity item){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        buildPortrait(item.author),
        Expanded(
          child: buildPostContent(item),
        ),
      ],
    );
  }

  buildPostContent(OscPostEntity item){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        buildTitle(item),
        buildDescription(item.body),
        buildBottom(item),
      ],
    );
  }

  buildPortrait(OscAuthor author){
    return Padding(
      padding: EdgeInsets.only(right: Dimens.gap_view_normal),
      child: OscPortraitWidget(id: author.id, portraitImageUrl: author.portrait,),
    );
  }

  buildTitle(OscPostEntity item){
    if(richTextTitle){
      return RichTextTitle(item: item);
    } else {
      return SmallWidgets.buildText(item.title, Colors.black, Dimens.font_sp14, fontWeight: FontWeight.bold);
    }
  }


  buildDescription(String msg){
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
      child: buildText(msg, Colors.black54, Dimens.font_sp10),
    );
  }


  buildBottom(OscPostEntity item){
    return Padding(
      padding: EdgeInsets.only(top: paddingChildVertical),
      child: Row(
        children: <Widget>[
          Text("@${item.author.name} ${TimelineUtil.formatByDateTime(DateTime.parse(item.pubDate), dayFormat: DayFormat.Full)}", style: MyTextStyle.LIST_BOTTOM,),
          Expanded(
            child: buildBottomItem("ic_comment_30", "${item.statistics.comment}"),
          ),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, String text){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smallest, fit: BoxFit.fitWidth,),
        Text(" $text", style: MyTextStyle.LIST_BOTTOM,)
      ],
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    List<OscPostEntity> tempList;
    await httpRepository.getSubListByToken(pageToken: pageToken, token: token).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscPostEntity> result = resp.result;
        tempList = resp.result.items;
        if(pageToken == null){
          list = tempList;
        } else {
          list.addAll(tempList);
        }
        pageToken = result.nextPageToken;
        if(result.requestCount > result.responseCount){
          controller.loadNoData();
        } else {
          controller.loadComplete();
        }
      }
    });
    if(mounted) {
      setState(() {
        size = list?.length??0;
        controller.refreshCompleted();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
